package com.sdp.right.control;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.sdp.core.bizc.annotation.ViewColumn;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.utils.UniqueCheckTools;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.right.db.sys_import_template.service.ISysImportTemplateService;
import com.sdp.right.db.sys_import_template_detail.service.ISysImportTemplateDetailService;
import com.sdp.right.entity.SysImportTemplate;
import com.sdp.right.entity.SysImportTemplateDetail;
import com.sdp.right.utils.RightConstants;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2023-10-18
 */
@RestController
@RequestMapping("/SysImportTemplateController")
public class SysImportTemplateController {

	@Autowired
	private Query query;
	
	@Autowired
	private UniqueCheckTools uniqueCheckTools;
	
	@Autowired
	private ISysImportTemplateService iSysImportTemplateService;
	
	@Autowired
	private ISysImportTemplateDetailService iSysImportTemplateDetailService;
	
	
	@PostMapping(value = "/page")
	public Result<?> page(@RequestBody DataCenter dataCenter) {
		return Result.ok(query.page(iSysImportTemplateService, SysImportTemplate.class, dataCenter));
	}
	
	@PostMapping(value = "/save")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> save(@RequestBody SysImportTemplate sysImportTemplate) {
		if(sysImportTemplate==null) {
			return Result.error("导入导出模板信息为空");
		}
		
		if(StringUtils.isEmpty(sysImportTemplate.getTemplateId())) {
			
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysImportTemplateService, SysImportTemplate.class, new String[] {"templateName"}, "templateId",sysImportTemplate, null, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("此模板名称已经存在");
			}
	
			iSysImportTemplateService.save(sysImportTemplate);
		}else {
			Result<?> r = uniqueCheckTools.isUniqueSingle(iSysImportTemplateService, SysImportTemplate.class, new String[] {"templateName"}, "templateId",null, sysImportTemplate, false);
			if(r==null || !r.isSuccess()) {
				return Result.error("此模板名称已经存在");
			}
			iSysImportTemplateService.updateById(sysImportTemplate);
		}
	
		return Result.ok();
		
	}
	
	@GetMapping(value = "/del")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> del(@RequestParam(name="templateId",required=true) String templateId) {
		if(StringUtils.isEmpty(templateId)) {
			return Result.error("需要删除的记录信息不完整");
		}
		iSysImportTemplateService.removeById(templateId);
		
		iSysImportTemplateDetailService.removeTemplateDetailByTemplateId(templateId);
		return Result.ok();
	}
	
	
	/**
	 * 初始化模板
	 * @param sysImportTemplate
	 * @return
	 */
	@PostMapping(value = "/initEntityInfo")
	@Transactional(rollbackFor=Exception.class)
	public Result<?> initEntityInfo(@RequestBody SysImportTemplate sysImportTemplate) {
		if(StringUtils.isEmpty(sysImportTemplate)) {
			return Result.error("模板信息不完整");
		}
		
		Map<String,SysImportTemplateDetail> oldDetailMap =  new HashMap<>();
		
		if(!StringUtils.isEmpty(sysImportTemplate.getTemplateId())) {
			//两次初始化的实体是否是同一个，如果是，将以前的详情信息保留
			SysImportTemplate oldTemplate = iSysImportTemplateService.getById(sysImportTemplate.getTemplateId());
			if(sysImportTemplate.getEntityClassName().equals(oldTemplate.getEntityClassName())) {
				List<SysImportTemplateDetail> oldDetail = iSysImportTemplateDetailService.querytemplateDetailByTemplateId(sysImportTemplate.getTemplateId());
				
				if(oldDetail!=null && oldDetail.size()>0) {
					for(SysImportTemplateDetail sitd : oldDetail) {
						oldDetailMap.put(sitd.getFieldName(), sitd);
					}
				}
			}
			
			//先删除以前的
			iSysImportTemplateService.removeById(sysImportTemplate.getTemplateId());
	
			iSysImportTemplateDetailService.removeTemplateDetailByTemplateId(sysImportTemplate.getTemplateId());
		}
		
		//添加模板信息
		sysImportTemplate.setSystemNo(ContextManager.getContextData(CoreConstantsEnum.header中的模块参数名.getCode()));
		iSysImportTemplateService.save(sysImportTemplate);
		
		List<SysImportTemplateDetail> templateDetailList = new ArrayList<>();
		
		try {
			Field[] fields = Class.forName(sysImportTemplate.getEntityClassName()).getDeclaredFields();
			int index = 1;
			TableField tableField; //字段注解
			ViewColumn viewColumn;//视图字段注解
			TableId tableId; //主键注解
			boolean isView = false;
			for (int i=0;i<fields.length;i++){
				Field field = fields[i];
				
				if(Modifier.toString(field.getModifiers()).indexOf("static")<0) {
					tableField = field.getAnnotation(TableField.class);
					viewColumn = field.getAnnotation(ViewColumn.class);
					tableId = field.getAnnotation(TableId.class);
					
					if(isView) {
						viewEntity(oldDetailMap, field, viewColumn, sysImportTemplate, templateDetailList, index);
						index++;
						continue;
					}
					
					if(viewColumn!=null) {
						isView = true;
						viewEntity(oldDetailMap, field, viewColumn, sysImportTemplate, templateDetailList, index);
						index++;
					}
					
					
					if(!isView) {
						if(tableField==null && tableId==null) {
							return Result.error(sysImportTemplate.getEntityClassName()+" 实体中，有字段未配置TableField 或者 TableId注解");
						}
						entity(oldDetailMap, field, tableField, tableId, sysImportTemplate, templateDetailList, index);
						index++;
					}
					
					
					
					
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.error("初始化失败");
		}
		
		//添加模板详情信息
		iSysImportTemplateDetailService.saveBatch(templateDetailList);
		return Result.ok(sysImportTemplate.getTemplateId());
	}
	
	private void entity(Map<String,SysImportTemplateDetail> oldDetailMap,
			Field field,
			TableField tableField,
			TableId tableId,
			SysImportTemplate sysImportTemplate,
			List<SysImportTemplateDetail> templateDetailList,
			int index) {
		SysImportTemplateDetail sitd = new SysImportTemplateDetail();
		if(oldDetailMap.size()>0 && oldDetailMap.containsKey(field.getName())) {
			sitd = oldDetailMap.get(field.getName());
			sitd.setTemplateId(sysImportTemplate.getTemplateId());
			sitd.setDbField(tableField==null?tableId.value():tableField.value());
			templateDetailList.add(sitd);
		}else {
			sitd.setFieldName(field.getName());
			sitd.setFieldType(field.getGenericType().toString());
			sitd.setFieldOrder(index);
			sitd.setFieldTitle(field.getName());
			sitd.setIsImport(RightConstants.是.getCode());
			sitd.setTemplateId(sysImportTemplate.getTemplateId());
			sitd.setDbField(tableField==null?tableId.value():tableField.value());
			templateDetailList.add(sitd);
		}
	}
	
	private void viewEntity(Map<String,SysImportTemplateDetail> oldDetailMap,
			Field field,
			ViewColumn viewColumn,
			SysImportTemplate sysImportTemplate,
			List<SysImportTemplateDetail> templateDetailList,
			int index) {
		SysImportTemplateDetail sitd = new SysImportTemplateDetail();
		if(oldDetailMap.size()>0 && oldDetailMap.containsKey(field.getName())) {
			sitd = oldDetailMap.get(field.getName());
			sitd.setTemplateId(sysImportTemplate.getTemplateId());
			sitd.setDbField(viewColumn.value());
			templateDetailList.add(sitd);
		}else {
			sitd.setFieldName(field.getName());
			sitd.setFieldType(field.getGenericType().toString());
			sitd.setFieldOrder(index);
			sitd.setFieldTitle(field.getName());
			sitd.setIsImport(RightConstants.是.getCode());
			sitd.setTemplateId(sysImportTemplate.getTemplateId());
			sitd.setDbField(viewColumn.value());
			templateDetailList.add(sitd);
		}
	}
}

